package com.example.javaapitest.common;

import com.alibaba.fastjson.JSONObject;
import io.restassured.response.Response;
import org.jsoup.helper.StringUtil;

import java.util.HashMap;
import java.util.Map;

import static io.restassured.RestAssured.given;

public class RunCaseJson {

    /*
     *post或get方式请求,返回响应报文（json格式）
     *@bodyString:json格式的请求报文体
     *@para:requestType post或get
     */
    public Response runCase(String requestType, String url, String header, String parameter, String bodyString){
        Map<String, String> headers = new HashMap<String,String>();
        if(!StringUtil.isBlank(header)){
            JSONObject jsonObject = JSONObject.parseObject(header);
            jsonObject.forEach((k,v) ->{
                headers.put(k, (String) v);
            });
        }
        // headers.put("tenantId", "626804036418404352");

        Map<String, String> parameters = new HashMap<String,String>();
        if(!StringUtil.isBlank(parameter)){
            JSONObject jsonObject = JSONObject.parseObject(parameter);
            jsonObject.forEach((k,v) ->{
                parameters.put(k, (String) v);
            });
        }

        if(StringUtil.isBlank(bodyString))
            bodyString = "";
        Response response = null;
        if(requestType.toLowerCase().equals("get"))
            response = given()
                    .contentType("application/json;charset=UTF-8")
                    .headers(headers)
                    .params(parameters)
                    .request()
                    .body(bodyString)
                    .get(url);
        else
            response = given()
                    .contentType("application/json;charset=UTF-8")
                    .headers(headers)
                    .params(parameters)
                    .request()
                    .body(bodyString)
                    .post(url);

        //打印格式化的参数
        //response.prettyPrint(); ////去掉部分日志 add by lrb 20181029

        return response;
    }

    public static void main(String[] args) {
        String s = "{\"orderTypeDate\":\"2021/8/22\"}";
        Response response = new RunCaseJson().runCase("get","http://172.19.102.42:7300/mock/60aa00d054915d0027aa70aa/exp/get",s,"","");
        System.out.println(response.asString());
    }
}
